<template>

  <div class="login">
    <vue-particles
            class="background"
            color="#dedede"
            :particleOpacity="0.7"
            :particlesNumber="80"
            shapeType="circle"
            :particleSize="4"
            linesColor="#dedede"
            :linesWidth="1"
            :lineLinked="true"
            :lineOpacity="0.4"
            :linesDistance="150"
            :moveSpeed="3"
            :hoverEffect="true"
            hoverMode="grab"
            :clickEffect="true"
            clickMode="push"
    >
    </vue-particles>
    <div class="input">
     <i-form ref="loginInfo" :model="loginInfo" :rules="ruleInline" v-show="isLogin">
       <div class="head">
         <div class="demo-avatar">
           <Avatar src="http://dd.ddandang.top/blog/images/images.jpg" size="150" />
         </div>
       </div>
       <FormItem prop="user">
         <i-input size="large" type="text" v-model="loginInfo.user" clearable placeholder="账号">
         </i-input>
       </FormItem>
       <FormItem prop="password">
         <i-input type="password" size="large" v-model="loginInfo.password"   placeholder="密码">
         </i-input>
       </FormItem>
       <FormItem>
         <Row :gutter="20">
           <i-col span="12" >
             <router-link to="/" class="link">
               <Tag color="primary" size="large">回到首页</Tag>
             </router-link>
           </i-col>
           <i-col span="12">
             <Tag color="blue" class="tag tags" size="large">
               <div @click="go('login')">
                 前往注册
               </div>
             </Tag>
           </i-col>
         </Row>
       </FormItem>
       <FormItem>
         <Button class="btn" :loading="loginInfo.loading" @click="login('loginInfo')" type="primary" shape="circle">登录</Button>
       </FormItem>
     </i-form>
     <i-form ref="registerInfo" :model="registerInfo" :rules="ruleCustom" v-show="!isLogin">
        <div class="head">
          <div class="demo-avatar">
            <Avatar src="http://dd.ddandang.top/blog/images/images.jpg" size="150" />
          </div>
        </div>
        <FormItem prop="nickname">
          <i-input size="large" type="text" v-model="registerInfo.nickname" clearable placeholder="用户名昵称">
          </i-input>
        </FormItem>
        <FormItem prop="account">
          <i-input size="large" type="text" @on-blur="judgeUsername()" v-model="registerInfo.account" clearable placeholder="账号">
          </i-input>
        </FormItem>
       <FormItem prop="newPassword">
         <i-input  size="large" type="password" v-model="registerInfo.newPassword" clearable placeholder="输入密码">

         </i-input>
       </FormItem>
       <FormItem prop="passwordCheck">
         <i-input size="large" type="password" v-model="registerInfo.passwordCheck" clearable placeholder="确认密码"></i-input>
       </FormItem>
        <FormItem>
          <Row :gutter="20">
            <i-col span="12" >
              <router-link to="/" class="link">
                <Tag color="primary" size="large">回到首页</Tag>
              </router-link>
            </i-col>
            <i-col span="12">

                <Tag color="blue" class="tag tags" size="large">
                  <div @click="go('register')">
                    前往登录
                  </div>
                </Tag>
            </i-col>
          </Row>
        </FormItem>
        <FormItem>
          <Button class="btn" :loading="registerInfo.loading" @click="register('registerInfo')" type="primary" shape="circle">注册</Button>
        </FormItem>
      </i-form>

    </div>
  </div>
</template>

<script>

  import{register, login, judgeUser} from "@/network/login";

  export default {
    name: "Login",
    data () {
      const validateNickname = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名！'));
        } else if(value.length > 7) {
          callback(new Error('昵称不能大于7个字符！'));
        } else {
          callback();
        }
      };
      const validateAccount = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入账号！'));
        } else if(value.length < 6||value.length > 16) {
          callback(new Error('账号在6-16位之间！'));
        } else{
          callback();
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码！'));
        } else if(value.length < 6) {
          callback(new Error('密码不少于6位数！'));
        }else {
          if (this.registerInfo.passwordCheck !== '') {
            // 对第二个密码框单独验证
            this.$refs.registerInfo.validateField('passwordCheck');
          }
          callback();
        }
      };
      const validatePassCheck = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码'));
        } else if (value !== this.registerInfo.newPassword) {
          callback(new Error('两次密码不同，请重新输入!'));
        } else {
          callback();
        }
      };
      return {
        //登录用户信息
        user: {
          userId: 0,
          username: '',
          nickname: '',
          position: '',
          avatar: ''
        },
        isLogin: true,
        loginInfo: {
          loading: false,
          user: '',
          password: ''
        },
        ruleInline: {
          user: [
            {required: true, message: '请输入用户名！', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码！', trigger: 'blur'},
            {type: 'string', min: 6, message: '密码不能少于6位数！', trigger: 'blur'}
          ]
        },
        registerInfo: {
          loading: false,
          //账号是否可以使用 默认可以
          isUser: true,
          nickname: '',
          account: '',
          newPassword: '',
          passwordCheck: '',
        },
        ruleCustom: {
          newPassword: [
            {validator: validatePass, trigger: 'blur'}
          ],
          passwordCheck: [
            {validator: validatePassCheck, trigger: 'blur'}
          ],
          nickname: [
            {validator: validateNickname, trigger: 'blur'}
          ],
          account: [
            {validator: validateAccount, trigger: 'blur'}
          ]
        }
      }
    },
    methods: {

      //用户登录
      login(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.loginInfo.loading = true;
            login(this.loginInfo.user, this.loginInfo.password).then(res => {
              if (res.code === 4001) {
                this.$Message.error({
                  background: true,
                  content: '用户名错误!'
                });
              }else if (res.code === 4002) {
                this.$Message.error({
                  background: true,
                  content: '密码错误!'
                });
              }else if (res.code === 2000) {
                this.loginMethod(res);
              }
              this.loginInfo.loading = false;
            }).catch(() => {
              this.$Message.error({
                background: true,
                content: '请求错误!'
              });
              this.loginInfo.loading = false;
            })
          } else {
            this.$Message.error({
              background: true,
              content: '请正确填写信息!'
            });
          }
        })
      },
      register(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.registerInfo.loading = true;
            if(!this.registerInfo.isUser) {
              this.$Message.error({
                background: true,
                content: '该账号已存在!',
                duration: 2
              });
              this.registerInfo.loading = false;
              return;
            }
            register(this.registerInfo.nickname, this.registerInfo.account,
                this.registerInfo.newPassword, this.registerInfo.passwordCheck).then(res => {
              if(res.code === 2000) {
                console.log(res)
                this.loginMethod(res);
              }else {
                this.$Message.error({
                  background: true,
                  content: '输入信息有误，两次密码不一致！'
                });
              }
            }).catch(() => {
              this.$Message.error({
                background: true,
                content: '注册失败！'
              });
            })
            this.registerInfo.loading = false;
          } else {
            this.registerInfo.loading = false;
            this.$Message.error({
              background: true,
              content: '请正确填写信息!'
            });
          }
        })
      },
      //注册登录之间切换
      go(type) {
        if(type === 'register'){
          this.$refs['registerInfo'].resetFields();
        }else {
          this.$refs['loginInfo'].resetFields();
        }
        this.isLogin = !this.isLogin
      },
      //判断用户名是否存在
      judgeUsername() {
        const username = this.registerInfo.account;
        judgeUser(username).then( res => {
          if(res.code !== 2000) {
            this.$Message.error({
              background: true,
              content: '该账号已存在!',
              duration: 2
            });
            this.registerInfo.isUser = false;
          }else {
            this.registerInfo.isUser = true;
          }
        })

      },
      loginMethod(res) {
        this.user.userId = res.data.userId;
        this.user.nickname = res.data.nickname;
        this.user.position = res.data.position;
        this.user.avatar = res.data.avatar;
        this.user.username = res.data.username;
        //将数据存到VueX中
        this.$store.commit("serUser", this.user);
        let token = res.data.token;
        this.$store.commit('setToken', token);
        //token存到本地
        window.localStorage.setItem("token", token);
        //将用户信息放到本地
        window.localStorage.setItem("user", JSON.stringify(this.user));
        this.$Message.success({
          background: true,
          content: '登录成功!'
        });
        this.$store.commit('changeIndex','1');
        this.$router.push({path: '/'})
      }
    }
  }
</script>

<style scoped>
  .background{
    background-image:url("http://dd.ddandang.top/blog/images/background1.jpg");
    background-repeat:no-repeat;
    background-attachment: fixed;
    background-size: cover;
    position:absolute;z-index:0;
    width: 100%;
    height: 100%;
  }
  .login {
    height: 100%;
    display:flex;
    justify-content: center;
    align-items: center;
  }
  .input {
    background-color: black;
    text-align: center;
    width: 500px;
  }
  .btn{
    width: 60%;
  }
  .head {
    margin-bottom: 20px;
  }

  .tags :hover {
    cursor: default;
  }

</style>
